package com.dxf.securitys.security;


import com.dxf.common.utils.RedisUtil;
import com.dxf.common.utils.ResponseUtil;
import com.dxf.common.utils.ResultJson;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登出业务逻辑类
 */
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisUtil redisUtil;

    public TokenLogoutHandler(TokenManager tokenManager, RedisUtil redisUtil) {
        this.tokenManager = tokenManager;
        this.redisUtil = redisUtil;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
        if (token != null) {
            //tokenManager.removeToken(token);
            //清空当前用户缓存中的权限数据
            String userName = tokenManager.getUserFromToken(token);
            try {
                redisUtil.del(userName);
            }catch (Exception e){
                ResponseUtil.out(response, ResultJson.ok());
                return;
            }
        }
        ResponseUtil.out(response, ResultJson.ok());
    }

}